package com.ruis.kotboot.common.util

import org.slf4j.LoggerFactory
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
import java.lang.RuntimeException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * http工具类
 * @author NorthLan at 2018/2/8
 */
object HttpUtil {
    private val logger = LoggerFactory.getLogger(HttpUtil::class.java)

    fun getRequest(): HttpServletRequest {
        return (RequestContextHolder.getRequestAttributes() as ServletRequestAttributes).request?:throw RuntimeException()
    }

    fun getResponse(): HttpServletResponse {
        return (RequestContextHolder.getRequestAttributes() as ServletRequestAttributes).response?:throw RuntimeException()
    }

    fun getRequestSync(): HttpServletRequest? {
        try {
            return (RequestContextHolder.getRequestAttributes() as ServletRequestAttributes).request?:throw RuntimeException()
        }catch (e:Exception){}
        return null
    }

    fun getResponseSync(): HttpServletResponse? {
        try {
            return (RequestContextHolder.getRequestAttributes() as ServletRequestAttributes).response?:throw RuntimeException()
        }catch (e:Exception){}
        return null
    }

    fun getIp(): String {
        return getRequest().remoteHost
    }
}